import { Component, Fragment } from "react";
import { departAdd, departDetailed } from "../../api/common";
import { message } from "antd";
import { withRouter } from "react-router-dom";
import FromCom from "components/form";
import Qs from "qs";
class Add extends Component {
  constructor(props) {
    super(props);
    this.state = {
      formLayout: {
        labelCol: { span: 2 },
        wrapperCol: { span: 22 }
      },
      isEdit: false,
      id: null,
      formItem: [
        {
          type: "Input",
          label: "部门名称",
          name: "name",
          required: true,
          style: { width: "200px" },
          placeholder: "请输入部门名称"
        },
        {
          type: "InputNumber",
          label: "人员数量",
          name: "number",
          required: true,
          min: 1,
          max: 100,
          style: { width: "200px" },
          placeholder: "请输入人员数量"
        },
        {
          type: "Radio",
          label: "禁启用",
          name: "status",
          required: true,
          options: [
            { label: "禁用", value: false },
            { label: "启用", value: true }
          ]
        },
        {
          type: "TextArea",
          label: "描述",
          name: "content",
          required: true,
          placeholder: "请输入描述内容"
        }
      ],
      editData: {},
      initialValues:{ status: false, number: 0 }
    };
  }
  // 生命周期
  componentDidMount() {
    // 实验证明 只有search传参刷新不会丢失
    const search = this.props.location.search;
    if (search) {
      const id = Qs.parse(search)["?id"];
      // setState这里是异步 打印console.log是弄不出来的 需要去其它方法里面打印 其实已经修改改了
      !!id && this.setState({ isEdit: true, id });
      this.edit(id);
    }
  }
  edit = async id => {
    const res = await departDetailed({ id });
    this.setState({ editData: res.data });
  };
  onFinish = async (params, form) => {
    const { id } = this.state;
    try {
      //  添加 修改
      if (id) {
        params.id = id;
      }
      const res = await departAdd(params);
      message.success(res.message);
      // 重置
      form.resetFields();
    } catch (error) {
      console.log(error);
    }
  };
  render() {
    const { formLayout, formItem, editData,initialValues } = this.state;
    return (
      <Fragment>
        <FromCom
          formItem={formItem}
          formLayout={formLayout}
          submit={this.onFinish}
          editData={editData}
          initialValues={initialValues}
        />
      </Fragment>
    );
  }
}

export default withRouter(Add);
